package controller

import (
  "awesomeProject/Response"
  "awesomeProject/dao"
  "awesomeProject/forms"
  "awesomeProject/utils"
  "fmt"
  "github.com/gin-gonic/gin"
  "net/http"
)

func GetLoginPage(c *gin.Context) {
  c.HTML(http.StatusOK, "login.html", gin.H{
    "title": "blogo：login page",
  })
}

// 登录逻辑
func DoLogin(c *gin.Context){
  // 解析字段
  PasswordLoginForm := forms.PasswordLoginForm{}

  //if err := c.ShouldBind(&PasswordLoginForm); err!=nil {
  //utils.HandleValidatorError(c, err)
  //return
  //}
  PasswordLoginForm.Username = c.Query("username")
  PasswordLoginForm.Password = c.Query("password")
  PasswordLoginForm.Captcha = c.Query("captcha")
  PasswordLoginForm.CaptchaId = c.Query("captchaId")

  fmt.Println("form: ", PasswordLoginForm)

  if !store.Verify(PasswordLoginForm.CaptchaId, PasswordLoginForm.Captcha, true){
    Response.Err(c, 200, 400, "验证码错误", "")
    return
  }

  user, ok := dao.FindUserInfo(PasswordLoginForm.Username, PasswordLoginForm.Password)
  if !ok {
    Response.Err(c, 200, 401, "用户未注册或密码错误", "")
    return
  }

  token := utils.CreateToken(c, user.AdminUserId, user.NickName, user.Locked)
  userinfoMap := HandleUserModelTopMap(user)
  userinfoMap["token"] = token

  Response.Success(c, http.StatusOK, "success", userinfoMap)
  //c.Header("x-token", token)
  //c.Redirect(http.StatusMovedPermanently, "/blogo/dashboard/page")

}

